package com.video.video.service.impl;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.video.common.constant.Constants;
import com.video.common.exception.ServiceException;
import com.video.common.utils.SendSmsUtil;
import com.video.common.utils.uuid.IdUtils;
import com.video.video.domain.DCommissionRecord;
import com.video.video.domain.DSystemSettings;
import com.video.video.domain.app.dto.AppUserRegisterDto;
import com.video.video.domain.app.dto.MemberDto;
import com.video.video.domain.vo.UserQuery;
import com.video.video.service.IDCommissionRecordService;
import com.video.video.service.IDSystemSettingsService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.video.common.utils.DateUtils;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.video.video.mapper.DUserMapper;
import com.video.video.domain.DUser;
import com.video.video.service.IDUserService;

/**
 * 客户Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-27
 */
@Service
public class DUserServiceImpl implements IDUserService
{
    @Autowired
    private DUserMapper dUserMapper;
    @Autowired
    private IDCommissionRecordService idCommissionRecordService;
    @Autowired
    private IDSystemSettingsService idSystemSettingsService;


    @Override
    public Integer getNumsByUserId(String userId) {
        return dUserMapper.getNumsByUserId(userId);
    }

    @Override
    public List<MemberDto> getMemberListByUserId(String userId) {
        //判断用户身份-除了代理查两级,其他的只查一级
        DUser dUser=dUserMapper.selectDUserById(userId);
        if(dUser == null){
            throw new ServiceException("会员不存在");
        }
        List<MemberDto> list =dUserMapper.getMemberListByUserId(userId);
        if(CollectionUtils.isNotEmpty(list) && dUser.getLevel().equals("4")){
            for (MemberDto memberDto : list) {
                memberDto.setSublevel(dUserMapper.getMemberListByUserId(memberDto.getId()));
                memberDto.setNumbers(dUserMapper.getNumsByUserId(memberDto.getId()));
            }
        }
        return list;
    }

    /**
     * 查询客户
     *
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public DUser selectDUserById(String id)
    {
        DUser dUser = dUserMapper.selectDUserById(id);

        //计算会员还有多少天到期

        if(dUser.getBecomeDue() == null){
            //没有设置 直接设置为0
            dUser.setDayNum(0);
        }else{
            //存在到期时间  判断到期时间 与当前时间的 差
            int betweenDays = DateUtils.differentDays(new Date(),dUser.getBecomeDue());
            if(betweenDays >= 0){
                dUser.setDayNum(betweenDays);
            }else{
                dUser.setDayNum(0);
            }
        }
        return dUser;
    }

    @Override
    public List<DUser> selectDUserAllList(DUser dUser) {
        return dUserMapper.selectDUserAllList(dUser);
    }

    /**
     * 查询客户列表
     *
     * @param dUser 客户
     * @return 客户
     */
    @Override
    public List<DUser> selectDUserList(UserQuery dUser)
    {
        return dUserMapper.selectDUserList(dUser);
    }

    @Override
    public List<Integer> listIdBecomeDue() {
        return dUserMapper.listIdBecomeDue();
    }

    @Override
    public void updateBecomeDueVip() {
        dUserMapper.updateBecomeDueVip();
    }

    /**
     * 新增客户
     *
     * @param dUser 客户
     * @return 结果
     */
    @Override
    public int insertDUser(DUser dUser)
    {
        dUser.setId(IdUtils.getId());
        dUser.setBalance(new BigDecimal("0"));//钱包余额
        dUser.setTotalAmount(new BigDecimal("0"));//返佣总额
        dUser.setCommissionBalance(new BigDecimal("0"));//返佣余额
        dUser.setCreateTime(DateUtils.getNowDate());

        if(dUser.getDayNum() != null){
            //设置到期时间
            dUser.setBecomeDue(DateUtils.afterDays(dUser.getDayNum()));
        }
        return dUserMapper.insertDUser(dUser);
    }

    /**
     * 修改客户
     *
     * @param dUser 客户
     * @return 结果
     */
    @Override
    public int updateDUser(DUser dUser)
    {


        //判断修改会员等级
        if(dUser.getLevel().equals("6") || dUser.getLevel().equals("7") || dUser.getLevel().equals("8")){
            //判断当前用户是否有上级
            if(!dUser.getPid().equals(0)){
                //查询当前会员上级
                DUser dUser1=dUserMapper.selectDUserById(dUser.getPid());
                if(dUser1 !=null){
                    //判断当前会员是否已经进行返佣
                    DCommissionRecord dCommissionRecord=new DCommissionRecord();
                    dCommissionRecord.setUid(dUser1.getId());
                    dCommissionRecord.setCoid(dUser.getId());
                    dCommissionRecord.setOid("0");//订单ID 为 0的，都是VIP 会员只推返佣
                    List<DCommissionRecord> list= idCommissionRecordService.selectVipRecordList(dCommissionRecord);
                    if(CollectionUtils.isEmpty(list)){
                        //判断是否享受分佣
                        if("Y".equals(dUser1.getIsCommission())){
                            //会员等级：1 一般用户2 VIP用户3 SVIP 4 代理（不优惠） 5 合伙人(不优惠、不返佣)
                            List<DSystemSettings> list2 =idSystemSettingsService.selectDSystemSettingsList(new DSystemSettings());
                            DSystemSettings settings=list2.get(0);

                            dCommissionRecord.setOrderAmount(new BigDecimal(0));
                            dCommissionRecord.setCommissionRate(new BigDecimal(0));

                            if(dUser1.getLevel().equals("6")){
                                dCommissionRecord.setCommissionAmount(settings.getVip1Amt());
                            }
                            if(dUser1.getLevel().equals("7")){
                                if(dUser.getLevel().equals("6")){
                                    dCommissionRecord.setCommissionAmount(settings.getVip1Amt());
                                }
                                if(dUser.getLevel().equals("7")){
                                    dCommissionRecord.setCommissionAmount(settings.getVip2Amt());
                                }

                            }
                            if(dUser1.getLevel().equals("8")){
                                if(dUser.getLevel().equals("6")){
                                    dCommissionRecord.setCommissionAmount(settings.getVip1Amt());
                                }
                                if(dUser.getLevel().equals("7")){
                                    dCommissionRecord.setCommissionAmount(settings.getVip2Amt());
                                }
                                if(dUser.getLevel().equals("8")){
                                    dCommissionRecord.setCommissionAmount(settings.getVip3Amt());
                                }

                            }

                            idCommissionRecordService.insertDCommissionRecord(dCommissionRecord);
                            //修改会员返佣金额
                            dUser1.setTotalAmount(dUser1.getTotalAmount().add(dCommissionRecord.getCommissionAmount()));
                            dUser1.setCommissionBalance(dUser1.getCommissionBalance().add(dCommissionRecord.getCommissionAmount()));
                            dUser1.setUpdateTime(DateUtils.getNowDate());
                            dUserMapper.updateDUser(dUser1);
                        }
                    }
                }

            }


        }

        dUser.setUpdateTime(DateUtils.getNowDate());
        if(dUser.getDayNum() != null){
            //设定到期时间
            dUser.setBecomeDue(DateUtils.afterDays(dUser.getDayNum()));
        }
        return dUserMapper.updateDUser(dUser);
    }

    @Override
    public int updateDUserInfo(DUser dUser) {
        dUser.setUpdateTime(DateUtils.getNowDate());
        return dUserMapper.updateDUser(dUser);
    }

    /**
     * 批量删除客户
     *
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteDUserByIds(String[] ids)
    {
        return dUserMapper.deleteDUserByIds(ids);
    }

    /**
     * 删除客户信息
     *
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteDUserById(String id)
    {
        return dUserMapper.deleteDUserById(id);
    }

    @Override
    public SendSmsResponse sendSms(String phone, String smsCode, String activeCode) {
        return SendSmsUtil.sendSms(phone,"SMS_253910178",activeCode);
    }
}
